﻿using Commands.Base;
using CommonLib.CacheOperation;
using CommonLib.NetOperation;
using CommonLib.SerializeOperation;
using DispatchingCenter.Base;
using DispatchingCenter.Dispatch;
using Events.Auth;
using Models.Auth;
using Models.Base;
using Models.Data;
using Models.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Commands.Auth
{
    /// <summary>
    /// 微信交互接口凭证命令
    /// </summary>
    public class AccessTokenCommand
    {
        #region 静态构造函数

        static AccessTokenCommand()
        {
            AutoUpdateCache.Add(CacheKeySet.AccessToken.ToString(), new AutoUpdateItem()
            {
                UpdateValue = (AutoUpdateItem autoUpdateItem) =>
                {
                    var accessTokenInfo = CommandHelper.GetWeChatResponseObject<AccessTokenInfo>(new AccessTokenCommandRequest());

                    autoUpdateItem.ExpiredSeconds = accessTokenInfo.ExpiresIn - 30;//预留过期时效，防止提前过期
                    autoUpdateItem.Value = accessTokenInfo;
                }
            });
        }

        /// <summary>
        /// 填充微信接口交互凭据
        /// </summary>
        /// <param name="e"></param>
        [DispatchBeforeActiveHandler()]
        public void FillAccessToken(DispatchEvent e)
        {
            IAccessTokenAuth accessTokenAuth = e as IAccessTokenAuth;
            if (accessTokenAuth == null)
            {
                return;
            }

            var getAccessTokenEvent = new GetAccessTokenEvent();
            Dispatcher.ActiveEvent(getAccessTokenEvent);

            accessTokenAuth.AccessToken = getAccessTokenEvent.AccessTokenInfo.AccessToken;
        }

        #endregion

        /// <summary>
        /// 获取微信交互接口凭证
        /// </summary>
        /// <param name="e"></param>
        [DispatchHandler(typeof(GetAccessTokenEvent))]
        public void GetAccessToken(GetAccessTokenEvent e)
        {
            e.AccessTokenInfo = AutoUpdateCache.GetValue<AccessTokenInfo>(CacheKeySet.AccessToken.ToString());
        }
    }
}
